<?php

namespace App\Ant\Excel\Imports;

use App\Ant\Jobs\ArchiveImportJob;
use App\Models\Company\Archive;
use App\Models\Company\Material;
use App\Models\Label;
use App\Models\System\Region;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMappedCells;
use Overtrue\Pinyin\Pinyin;

class MaterialImport implements ToCollection, WithChunkReading
{

    protected $items;

    protected $relationModel;

    protected $label;

    public function __construct(Model $model)
    {
        $this->init();
        $this->relationModel = $model;
        $name = $this->relationModel->region->name . '建材公司';
        $this->label = Label::where('name', $name)->first();
        if ($this->label == null) {
            $this->label = new Label([
                'name' => $name,
                'is_state' => true
            ]);
            $this->label->save();
        }
    }

    private function init()
    {
        $this->items = new Collection();
    }

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        $collection->each(function ($item) {
            if ($item[0] == '企业名称') return;
            $data = [
                'name' => $item[0],
                'region_id' => $this->relationModel->region_id,
                'type' => $item[5],
                'business_scope' => $item[10],
                'location' => $item[8],
                'credit_code' => $item[3],
                'legal_person' => $item[4],
                'established_at' => $item[6],
                'capital' => $item[7],
                'email' => $item[9],
                'tel' => $item[12],
                'more_tel' => $item[13],
                'website' => $item[11],
                'task_id' => $this->relationModel->id,
                'is_state' => false,
                'category_id' => $this->relationModel->category_id,
                'is_top' => $this->relationModel->is_top,
                'label_id' => $this->label->id
            ];
            $this->items->push($data);
        });
        $this->relationModel->increment('count', $this->items->count());
        if ($this->items->isNotEmpty()) {
            Material::insert($this->items->toArray());
        }
        $this->init();
    }

    public function chunkSize(): int
    {
        return 1000;
    }
}